package com.demo.las.service;

import com.demo.las.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthService {

    @Autowired
    private UserService userService;

    @Autowired
    private SessionService sessionService;

    public Map<String, Object> login(String usernameOrEmail, String password) {
        User user = userService.findByUsernameOrEmail(usernameOrEmail);
        
        if (user == null || !password.equals(user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        if (user.getStatus() != User.UserStatus.ACTIVE) {
            throw new RuntimeException("账户已被禁用");
        }

        String sessionId = sessionService.createSession(user);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "登录成功");
        result.put("sessionId", sessionId);
        result.put("user", user);
        return result;
    }

    public User register(String username, String password, String email) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setStatus(User.UserStatus.ACTIVE);
        
        return userService.createUser(user);
    }
    
    public void logout(String sessionId) {
        sessionService.removeSession(sessionId);
    }
}
